package com.wwx.demo.servlet;

import com.alibaba.fastjson.JSON;
import com.wwx.demo.entity.Result;
import com.wwx.demo.entity.Tiger;
import com.wwx.demo.service.api.TigerService;
import com.wwx.demo.service.impl.TigerServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "TigerServletGetById", value = "/TigerServletGetById")
public class TigerServletGetById extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、创建 Service 对象
        TigerService tigerService = new TigerServiceImpl();

        // 2、从请求参数中获取 id 值
        // ※友情提示：这里我们是先写的后端，所以将来写前端的时候，请求参数名要和这里的设定一致
        String tigerId = request.getParameter("tigerId");

        // 3、调用 Service 方法执行查询
        Tiger tiger = tigerService.getTigerById(tigerId);

        // 4、把查询结果转换为 JSON 字符串
        String jsonString = JSON.toJSONString(Result.ok(tiger));

        // 5、返回响应
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(jsonString);
    }
}
